package com.moqianfan.mcuassistant.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.moqianfan.mcuassistant.R;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/11/18.
 * 定时计数器页面
 */

public class TimeActivity extends BaseActivity{
    @BindView(R.id.CrystalSpin)
    Spinner spin;
    private static final String[] Crystal = {"6MHz", "11.0592MHz", "12MHz",
            "24MHz", "48MHz"};
    @BindView(R.id.T_Spin)
    Spinner TSpin;
    private static final String[] T_Spin = {"T0", "T1"};
    @BindView(R.id.ModelSpin)
    Spinner ModelSpin;
    private static final String[] Model_Spin = {"定时", "计数"};
    @BindView(R.id.MannerSpin)
    Spinner MannerSpin;
    private static final String[] Manner_Spin = {"方式0-13位定时/计数器",
            "方式1-16位定时/计数器", "方式2-8位自动重装定时/计数器", "方式3-2个8位定时/计数器"};
    private static final String[] Manner_Spin1 = {"方式0-13位定时/计数器",
            "方式1-16位定时/计数器", "方式2-8位自动重装定时/计数器"};
    protected static final String TAG = "TimerActivity";

    Button TimerCBtn, TimerASMBtn, Clear_Code;
    // 常用参数
    public int Mode = 0; // 定时计数选择
    public int Manner = 0; // 工作方式选择
    public double Crysta = 0; // 晶振大小选择
    public int Time = 0; // 定时器选择标志
    public int Time_Max = 8192;// 最大定时范围
    byte[] Tmod = new byte[8];
    String TMOd;
    String Thx, Tlx;
    @BindView(R.id.TimeChange)
    TextView TimeInfo;
    @BindView(R.id.LableTv)
    TextView LableTv;
    @BindView(R.id.Tmod)
    TextView TMOD;
    @BindView(R.id.THx)
    TextView THx;
    @BindView(R.id.TLx)
    TextView TLx;
    @BindView(R.id.InputTime)
    EditText InputTime;
    @BindView(R.id.CodeEdit)
    EditText CodeEdit;
    ClipboardManager myClipboard;
    long editclickTime = 0;

    @Override
    public void findViews() {
        setContentView(R.layout.activity_tools_timer);
    }

    @Override
    public void initViews() {
        InputTime.addTextChangedListener(Input);
        CodeEdit.setFocusable(false);
        // 晶振列表
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, Crystal);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin.setAdapter(adapter);
        spin.setSelection(2);
        spin.setOnItemSelectedListener(spinListener);

        // 定时器列表
        ArrayAdapter<String> Tadapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, T_Spin);
        Tadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        TSpin.setAdapter(Tadapter);
        TSpin.setOnItemSelectedListener(spinListener);

        // 工作模式列表
        ArrayAdapter<String> Modeladapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, Model_Spin);
        Modeladapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ModelSpin.setAdapter(Modeladapter);
        ModelSpin.setOnItemSelectedListener(spinListener);

        // 工作方式列表
        ArrayAdapter<String> Manneradapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, Manner_Spin);
        Manneradapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        MannerSpin.setAdapter(Manneradapter);
        MannerSpin.setOnItemSelectedListener(spinListener);
    }

    @Override
    public void initDatas() {
        Mode = 0; // 定时计数选择
        Manner = 0; // 工作方式选择
        Crysta = 6; // 晶振大小选择
        Time = 0; // 定时器选择标志
        Time_Max = 16384;// 最大定时范围
        for (int i = 0; i < Tmod.length; i++)
            Tmod[i] = 0;

        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    }

    /**
     * TMOD寄存器控制监听
     */
    private AdapterView.OnItemSelectedListener spinListener = new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> v, View arg1, int postion,
                                   long arg3) {
            int id = v.getId();
            if (id == R.id.ModelSpin) {
                switch (postion) {
                    case 0:
                        Mode = 0;
                        if (Time == 0) {
                            Tmod[2] = 0;
                        } else if (Time == 1) {
                            Tmod[6] = 0;
                        }

                        break;
                    case 1:
                        Mode = 1;
                        if (Time == 0) {
                            Tmod[2] = 1;
                        } else if (Time == 1) {
                            Tmod[6] = 1;
                        }

                        break;

                }
            } else if (id == R.id.CrystalSpin) {
                switch (postion) {
                    case 0:
                        Crysta = 6;
                        break;
                    case 1:
                        Crysta = 11.0592;
                        break;
                    case 2:
                        Crysta = 12;
                        break;
                    case 3:
                        Crysta = 24;
                        break;
                    case 4:
                        Crysta = 48;
                        break;

                }
            } else if (id == R.id.T_Spin) {
                switch (postion) {
                    case 0:
                        Time = 0;
                        Tmod[0] |= Tmod[4];
                        Tmod[1] |= Tmod[5];
                        Tmod[2] |= Tmod[6];
                        Tmod[3] = 0;
                        Tmod[4] = 0;
                        Tmod[5] = 0;
                        Tmod[6] = 0;
                        Tmod[7] = 0;

                        break;
                    case 1:
                        Time = 1;
                        ArrayAdapter<String> Manneradapter = new ArrayAdapter<>(
                                getBaseContext(),
                                android.R.layout.simple_spinner_item, Manner_Spin1);
                        Manneradapter
                                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        MannerSpin.setAdapter(Manneradapter);
                        Tmod[4] |= Tmod[0];
                        Tmod[5] |= Tmod[1];
                        Tmod[6] |= Tmod[2];
                        Tmod[0] = 0;
                        Tmod[1] = 0;
                        Tmod[2] = 0;
                        Tmod[3] = 0;
                        Tmod[7] = 0;
                        break;

                }
            } else if (id == R.id.MannerSpin) {
                switch (postion) {
                    case 0:
                        Manner = 0;
                        if (Time == 0) {
                            Tmod[0] = 0;
                            Tmod[1] = 0;
                        } else if (Time == 1) {
                            Tmod[4] = 0;
                            Tmod[5] = 0;
                        }

                        Time_Max = 8192;
                        break;
                    case 1:
                        Manner = 1;
                        if (Time == 0) {
                            Tmod[0] = 1;
                            Tmod[1] = 0;
                        } else if (Time == 1) {
                            Tmod[4] = 1;
                            Tmod[5] = 0;
                        }
                        Time_Max = 65536;
                        break;
                    case 2:
                        Manner = 2;
                        if (Time == 0) {
                            Tmod[0] = 0;
                            Tmod[1] = 1;
                        } else if (Time == 1) {
                            Tmod[4] = 0;
                            Tmod[5] = 1;
                        }
                        Time_Max = 256;
                        break;
                    case 3:
                        if (Time == 1)
                            Manner = 3;
                        if (Time == 0) {
                            Tmod[0] = 1;
                            Tmod[1] = 1;
                        } else if (Time == 1) {
                            Tmod[4] = 1;
                            Tmod[5] = 1;
                        }
                        Time_Max = 256;
                        break;

                }
            }
            if (Mode == 0) {
                LableTv.setText("定时时间(us)");
                InputTime.setHint("请输入");
                DecimalFormat df = new DecimalFormat("###0");
                TimeInfo.setText("定时范围:0~"
                        + df.format(Time_Max * 12.0 / Crysta) + "us");
            } else {
                LableTv.setText("计数初值");
                InputTime.setHint("请输入");
                TimeInfo.setText("计数范围:0~" + Time_Max + "次");
            }
            TMOd = bytesToHexString(Tmod);
            if (TMOd.length() == 1)
                TMOd = '0' + TMOd;

            TMOD.setText("TMOD=" + TMOd + "H");

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }

    };

    /**
     * TMOD数组转换为string型
     */
    public static String bytesToHexString(byte[] bArray) {
        StringBuilder sb = new StringBuilder(bArray.length);
        String sTemp;
        for (int i = bArray.length - 1; i > -1; i--) {
            sTemp = Integer.toBinaryString(0x1 & bArray[i]);
            sb.append(sTemp);
        }
        return Long.toHexString(Long.parseLong(sb.toString(), 2)).toUpperCase();
    }

    private TextWatcher Input = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String str = s.toString();
            String hex;
            String hex1 = "";
            try {
                int Dec = Time_Max
                        - (int) (Integer.parseInt(str, 10) * Crysta / 12.0);
                if (Integer.parseInt(str, 10) > Time_Max * 12.0 / Crysta) {
                    Toast.makeText(
                            getApplication(),
                            "定时范围最大为：" + (int) (Time_Max * 12.0 / Crysta)
                                    + "请重新输入！", Toast.LENGTH_LONG).show();
                    hex1 = "0000";
                    InputTime.getText().clear();
                } else {
                    hex1 = Integer.toHexString(Dec).toUpperCase();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            if (hex1.length() == 0) {
                hex = "0000";
            } else if (hex1.length() == 1) {
                hex = "000" + hex1;
            } else if (hex1.length() == 2) {
                hex = "00" + hex1;
            } else if (hex1.length() == 3) {
                hex = "0" + hex1;
            } else {
                hex = hex1;
            }
            Log.d(TAG, "hex=" + hex);
            Log.d(TAG, "hex1=" + hex1);
            byte[] arry = hex.getBytes();
            byte[] arryH = new byte[2];
            byte[] arryL = new byte[2];
            if (Manner == 2) {
                arryH[1] = arry[3];
                arryH[0] = arry[2];
                arryL[1] = arryH[1];
                arryL[0] = arryH[0];
            } else {
                arryH[1] = arry[3];
                arryH[0] = arry[2];
                arryL[1] = arry[1];
                arryL[0] = arry[0];
            }

            Log.d(TAG, "arryH[0]" + arryH[0]);
            Log.d(TAG, "arryH[1]" + arryH[1]);

            Log.d(TAG, "arryL[0]" + arryL[0]);
            Log.d(TAG, "arryL[1]" + arryL[1]);
            if (arryH[0] >= 'A' && arryH[0] <= 'F')
                Tlx = "0" + new String(arryH);
            else
                Tlx = new String(arryH);
            if (arryL[0] >= 'A' && arryL[0] <= 'F')
                Thx = "0" + new String(arryL);
            else
                Thx = new String(arryL);
            if (Time == 0) {
                THx.setText("TH0=" + Thx + "H");
                TLx.setText("TL0=" + Tlx + "H");
            } else if (Time == 1) {
                THx.setText("TH1=" + Thx + "H");
                TLx.setText("TL1=" + Tlx + "H");
            }

        }
    };

    @OnClick({R.id.image_close, R.id.CodeEdit,R.id.TimerASMBtn,R.id.TimerCBtn,R.id.Clear_Code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_close:
                finish();
                break;
            case R.id.CodeEdit:
                if (System.currentTimeMillis() - editclickTime > 500) {
                    editclickTime = System.currentTimeMillis();
                } else {
                    ClipData myClip;
                    String text = CodeEdit.getText().toString();//如果有内容直接添加就好
                    if (!TextUtils.isEmpty(text)) {
                        myClip = ClipData.newPlainText("text", text);//text是内容
                        myClipboard.setPrimaryClip(myClip);
                        Toast.makeText(this, "内容已复制", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.TimerASMBtn:
                String code = "";
                code += "ORG 0000H\n";
                code += "SJMP MAIN\n";
                if (Time == 0) {
                    code += "ORG 000BH  ;中断入口地址\n";
                    code += "SJMP Timer0Interrupt\n";
                    code += "MAIN:\n		MOV SP,#60H\n";
                    code += "		LCALL InitTimer0;初始化中断子函数\n";
                    code += "		LOOP:\n";
                    code += " 		;添加主函数代码\n";
                    code += "		LJMP LOOP\n";

                    code += "InitTimer0:\n";
                    code += "		MOV TMOD,#" + TMOd + "H\n";
                    code += "		MOV TH0,#" + Thx + "H\n";
                    code += "		MOV TL0,#" + Tlx + "H\n";
                    code += "		SETB EA\n";
                    code += "		SETB ET0\n";
                    code += "		SETB TR0\n";
                    code += "		RET\n";

                    code += "Timer0Interrupt:\n";
                    code += "		PUSH DPH\n		PUSH DPL\n		PUSH ACC\n";
                    if (Manner != 2) {
                        code += "		MOV TH0,#" + Thx + "H\n";
                        code += "		MOV TL0,#" + Tlx + "H\n";
                    }

                    code += " ;========================\n";
                    code += " ;中断处理代码\n";
                    code += " ;========================\n";
                    code += "		POP ACC\n		POP DPL\n		POP DPH\n		RETI\n		END";
                } else if (Time == 1) {

                    code += "ORG 001BH  ;中断入口地址\n";
                    code += "SJMP Timer1Interrupt\n";
                    code += "MAIN\n		MOV SP,#60H\n";
                    code += "		LCALL InitTimer1;初始化中断子函数\n";
                    code += "		LOOP:\n";
                    code += " 		;添加主函数代码\n";
                    code += "		LJMP LOOP\n";

                    code += "InitTimer1:	;中断初始化\n";
                    code += "		MOV TMOD,#" + TMOd + "H\n";
                    code += "		MOV TH1,#" + Thx + "H\n";
                    code += "		MOV TL1,#" + Tlx + "H\n";
                    code += "		SETB EA\n";
                    code += "		SETB ET1\n";
                    code += "		SETB TR1\n";
                    code += "		RET\n";

                    code += "Timer1Interrupt:\n";
                    code += "		PUSH DPH\n		PUSH DPL\n		PUSH ACC\n";
                    if (Manner != 2) {
                        code += "		MOV TH1,#" + Thx + "H\n";
                        code += "		MOV TL1,#" + Tlx + "H\n";
                    }

                    code += " ;========================\n";
                    code += " ;中断处理代码\n";
                    code += " ;========================\n";
                    code += "		POP ACC\n		POP DPL\n		POP DPH\n		RETI\n		END";
                }
                CodeEdit.setText(code);
                break;
            case R.id.TimerCBtn:
                String Ccode = "";
                Ccode += "#include <reg51.h>\n";
                Ccode += "void InitTimer(void);\n";
                Ccode += "void main(void)\n";
                Ccode += "{\n  InitTimer();\n}\n";
                if (Time == 0) {
                    Ccode += "void InitTimer(void)\n{\n";
                    Ccode += "	TMOD = 0x" + TMOd + ";\n";
                    Ccode += "	TH0 = 0x" + Thx + ";\n";
                    Ccode += "	TL0 = 0x" + Tlx + ";\n";
                    Ccode += "	EA = 1;\n";
                    Ccode += "	ET0 = 1;\n";
                    Ccode += "	TR0 = 1;\n}\n";
                    Ccode += "void Timer0Interrupt(void) interrupt 1";
                    Ccode += "	TH0 = 0x" + Thx + ";\n";
                    Ccode += "	TL0 = 0x" + Tlx + ";\n";
                    Ccode += " /*========================\n";
                    Ccode += " ;中断处理代码\n";
                    Ccode += " ;========================*/\n}";
                } else {
                    Ccode += "void InitTimer(void)\n{\n";
                    Ccode += "	TMOD = 0x" + TMOd + ";\n";
                    Ccode += "	TH1 = 0x" + Thx + ";\n";
                    Ccode += "	TL1 = 0x" + Tlx + ";\n";
                    Ccode += "	EA = 1;\n";
                    Ccode += "	ET1 = 1;\n";
                    Ccode += "	TR1 = 1;\n}\n";
                    Ccode += "void Timer1Interrupt(void) interrupt 3\n{\n";
                    Ccode += "	TH1 = 0x" + Thx + ";\n";
                    Ccode += "	TL1 = 0x" + Tlx + ";\n";
                    Ccode += " /*========================\n";
                    Ccode += " ;中断处理代码\n";
                    Ccode += " ;========================*/\n}";
                }
                CodeEdit.setText(Ccode);
                break;
            case R.id.Clear_Code:
                if (CodeEdit.getText() != null)
                    CodeEdit.getText().clear();
                if (InputTime.getText() != null)
                    InputTime.getText().clear();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(R.anim.push_right_in,
                    R.anim.push_right_out);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }
}
